package cn.doyens.service.imp;

import cn.doyens.bean.Account;
import cn.doyens.dao.AccountMapper;
import cn.doyens.service.AccountService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service("AccountService")
public class AccountServiceImp implements AccountService {

    @Autowired
    private AccountMapper  ma;
    @Override
    public List<Account> findAll() {
        List<Account> all = ma.findAll();
        for (Account account : all) {
            System.out.println(account);
        }
        return all;
    }

    @Override
    public PageInfo<Account> findAl(Integer page) {
        //当前第几页（默认值为第一页），每页显示5条记录
        PageHelper.startPage(page,5);

//               查询所有的医生数据
        List<Account> doctors = ma.findAl();
//        获得分页的结果对象
        PageInfo<Account> p = new PageInfo<>(doctors);
/*
以上三步顺序不能打乱
*/
        return p;
    }

    @Transactional
    @Override
    public void zu(int id1, int id2, int money) {
        ma.up1(id1,money);
       // int i=5/0;
        ma.up2(id2,money);
    }

    @Override
    public void insert(String name, String sex, Date date, String bumen) {
        ma.insert(name, sex, date, bumen);
        JedisPool jedisPool = new JedisPool();
        Jedis jedis = jedisPool.getResource();
        jedis.del("acclist");
        jedis.close();
        jedisPool.close();
    }

    @Override
    public List<Account> redis() {
        JedisPool jedisPool = new JedisPool();
        Jedis jedis = jedisPool.getResource();
        ObjectMapper objectMapper = new ObjectMapper();
        if (jedis.lrange("acclist",0,-1).size()<=0){
            List<Account> all = ma.findAll();
            System.out.println("进dao找的");
            for (Account account : all) {
                try {
                    jedis.rpush("acclist",objectMapper.writeValueAsString(account));
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }
            }else {
            System.out.println("redis里有");
        }
        ArrayList<Account> accounts = new ArrayList<>();
        List<String> acclist = jedis.lrange("acclist", 0, -1);
        for (String s : acclist) {
            try {
                Account account = objectMapper.readValue(s, Account.class);
                accounts.add(account);
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
        jedis.close();
        jedisPool.close();
        return accounts;
}
}
